package com.tuyrt.hi.concurrent_demo.coroutines

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * author: Administrator on 2021/6/17.
 * desc:
 */
object CoroutineScene {
    private const val TAG = "CoroutineScene"

    /**
     *  依次启动三个子线程，并且同步的方式拿到他们的返回值，进而更新UI
     */
    fun startScene1() {
        GlobalScope.launch(Dispatchers.Main) {
            Log.e(TAG, "coroutine is running. " )
            val result1 = request1()
            val result2 = request2(result1)
            val result3 = request3(result2)

            updateUI(result3)
        }

        Log.e(TAG, "coroutine has launched. " )
    }

    private fun updateUI(result3: String) {
        Log.e(TAG, "updateUI work on ${Thread.currentThread().name}" )
        Log.e(TAG, "parameter: $result3")
    }

    suspend fun request1(): String {
        delay(2 * 1000)
        Log.e(TAG, "request1 work on ${Thread.currentThread().name}")
        return "result from request1"
    }

    suspend fun request2(result1: String): String {
        delay(2 * 1000)
        Log.e(TAG, "request2 work on ${Thread.currentThread().name}")
        return "result from request2"
    }

    suspend fun request3(result2: String): String {
        delay(2 * 1000)
        Log.e(TAG, "request3 work on ${Thread.currentThread().name}")
        return "result from request3"
    }
}